package com.lsh.oms.core.service.order.ka;


import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.model.order.OrderSignHead;
import com.lsh.oms.core.service.order.AbstractOrderService;
import org.springframework.stereotype.Service;

/**
 * 订单发货service
 * @author peter
 */
@Service
@Deprecated
public class OrderReceiptKAService extends AbstractOrderService {

//    private static Logger logger = LoggerFactory.getLogger(OrderReceiptKAService.class);
//
//    @Autowired
//    private ShippingOrderService shippingService;
//
//    @Autowired
//    private SignOrderService signOrderService;
//
//    @Autowired
//    private EsProxy esProxy;


//    /**
//     * 创建签收单
//     *
//     * @param orderHead 订单信息
//     * @param logSign   唯一标识
//     * @return 返回信息
//     */
//    @Transactional
//    public CommonResult<Object> createReceiptOrder(OrderHead orderHead, String logSign) {
//
//        Long orderCode = orderHead.getOrderCode();
//
//        OrderShippingHeadWithBLOBs osh = shippingService.getBolbs(orderCode);
//        if (osh == null) {
//            throw new BusinessException(ReturnCode.REQUEST_FAIL, "此订单未生成发货单.请查询");
//        }
//
//        OrderSignHead oshHead = signOrderService.getSignHeadByOrderId(orderCode, false);
//        CommonResult<Object> res = new CommonResult<>();
//        if (oshHead != null) {
//            if (oshHead.getPayStatus() == 2) {
//                throw new BusinessException(ReturnCode.REQUEST_FAIL, "【KA】签收单已支付不能再次签收");
//            }
//
//            res.setData(oshHead);
//            res.setCode(ReturnCode.REQUEST_SUCCESS);
//            return res;
//        }
//
//        OrderSignHead orderSignHead = this.createReceiptBill(orderHead, osh, null, logSign);
//        if (orderSignHead != null) {
//
//            res.setData(orderSignHead);
//            res.setCode(ReturnCode.REQUEST_SUCCESS);
////            this.notifyEs(orderCode, osh, OrderFactory.getMarketName(orderHead), OrderFactory.getProviderId(orderHead), logSign);
//        } else {
//            res.setCode(ReturnCode.REQUEST_FAIL);
//        }
//
//        return res;
//    }

//    /**
//     * @param orderHead 订单信息
//     * @param osh       发货单信息
//     * @param logSign   信息标识
//     * @return OrderSignHead
//     */
//    private OrderSignHead createReceiptBill(OrderHead orderHead, OrderShippingHeadWithBLOBs osh, Integer receiptTime, String logSign) {
//        Long orderCode = orderHead.getOrderCode();
//        List<OrderShippingDetail> shippingDetails = shippingService.getDetails(osh.getShippingOrderId());
//
//        JSONObject extJson = JSON.parseObject(orderHead.getExt());
//        String providerId = extJson.getString("providerId");
//        if (StringUtils.isBlank(providerId)) {
//            throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单信息中没有供商信息，请联系相关人员处理");
//        }
//
//        Map<Integer,OrderShippingDetail> detailMap = shippingDetails.stream().collect(Collectors.toMap(OrderShippingDetail::getItemCode, shippingDetail -> shippingDetail));
//
//        //请求商品服务 商品信息
////        Map<String, Good> code2GoodMap = this.goodsServiceProxy.requestCode2Goods(orderCode, orderHead.getParentOrderCode(), providerId, orderHead.getVenderId(), logSign);
//
////        Map<String, Good> code2GoodMap = this.goodsServiceProxy.requestItem2Goods(orderCode, orderHead.getParentOrderCode(), providerId, orderHead.getVenderId(), logSign);
//        //TODO:请求签收计算服务
//        Map<Long, BigDecimal> orderReceiptItem = new HashMap<>();
//        CalOrderContent calOrderContent = this.orderReceipt(orderReceiptItem, osh, shippingDetails, logSign);
//        CalOrderReceiptContent receipt = calOrderContent.getReceipt();
//        CalOrderReturnContent returnOrder = calOrderContent.getReturnContent();
//        if (returnOrder != null) {
//            logger.info(orderCode + "-returnOrder-" + JSON.toJSONString(returnOrder));
//        }
//
//        CalOrderReceiptHead head = receipt.getHead();
//        List<CalOrderReceiptDetail> detailList = receipt.getDetailList();
//
//        OrderSignHead oshHead = OrderFactory.createSignHead(orderCode, orderHead, osh, head, receiptTime);
//
//        long receiptOrderId = IdGenerator.genId();
//        oshHead.setReceiptOrderId(receiptOrderId);
//
//        JSONObject extObject = head.getExt();
//        JSONObject headInfo = extObject.getJSONObject("head_info");
//        headInfo.put("floor_money", String.valueOf(oshHead.getFloorMoney().setScale(2, BigDecimal.ROUND_HALF_UP)));
//        headInfo.put("money", String.valueOf(oshHead.getMoney().setScale(2, BigDecimal.ROUND_HALF_UP)));
//        extObject.put("head_info", headInfo);
//        oshHead.setExt(extObject.toJSONString());
//        List<OrderSignDetail> signDetails = OrderFactory.receiptDetails(detailList, orderHead, receiptOrderId, detailMap, oshHead, logSign);
//
//        oshHead.setDetails(signDetails);
//        Integer paytype = oshHead.getPayType();
//        boolean statusFlag = false;
//        if (paytype != null && paytype >= 1) {
//            statusFlag = true;
//        }
//        boolean kaFlag = true;
//
//        if (!signOrderService.saveOrUpdateData(oshHead, logSign,statusFlag,kaFlag)) {
//            throw new BusinessException(ReturnCode.REQUEST_FAIL, "添加签收单失败");
//        }
//
//        return oshHead;
//    }


//    /**
//     * @param orderReceiptItem 签收数量
//     * @param osh              发货单信息
//     * @param shippingDetails  发货详情
//     * @param orderHead        订单信息
//     * @param logSign          唯一标识
//     * @return JSONObject
//     */
//    private CalOrderContent orderSign(Map<Long, BigDecimal> orderReceiptItem, OrderShippingHeadWithBLOBs osh, List<OrderShippingDetail> shippingDetails, OrderHead orderHead, String logSign) {
//        CalOrderContent calOrderContent;
//        try {
//            calOrderContent = orderReceiptByItem(orderReceiptItem, osh, shippingDetails, logSign);
//            if (calOrderContent == null || calOrderContent.getReceipt() == null) {
//                logger.info(logSign + "订单号" + orderHead.getOrderCode() + ",请求签收计算服务返回报文为空。");
//                throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务返回报文为空。");
//            }
//        } catch (Throwable e) {
//            logger.error(logSign + "订单号" + orderHead.getOrderCode() + ",请求签收计算服务失败。");
//            logger.error(e.getMessage(), e);
//            throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务失败。");
//        }
//
//        return calOrderContent;
//    }

//    /**
//     * @param detailList     签收详情
//     * @param orderHead      订单信息
//     * @param receiptOrderId 签收单ID
//     * @param detailMap       商品服务信息
//     * @param logSign        唯一标识
//     * @return List<OrderSignDetail>
//     */
//    private List<OrderSignDetail> receiptDetails(List<CalOrderReceiptDetail> detailList, OrderHead orderHead, Long receiptOrderId, Map<Integer,OrderShippingDetail> detailMap, String logSign) {
//        List<OrderSignDetail> signDetails = new ArrayList<>();
//        int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
//        try {
//            for (CalOrderReceiptDetail detail : detailList) {
//                if (detail == null) {
//                    logger.info(logSign + "订单号" + orderHead.getOrderCode() + ",签收计算服务解析明细为空。");
//                    throw new BusinessException(ReturnCode.REQUEST_FAIL, "此订单未生成发货单.请查询");
//                }
//                Integer itemCode = detail.getItemCode();
//                logger.info("签收计算服务详情 " + JSON.toJSONString(detail));
////                logger.info("商品服务返回结果 " + JSON.toJSONString(codeMaps));
//                OrderSignDetail signDetail = new OrderSignDetail();
//                JSONObject ext = detail.getExt();
//                signDetail.setReceiptOrderId(receiptOrderId);
//                signDetail.setRealQty(detail.getRealQty());
//                signDetail.setPackageId(ext.getInteger("package_id"));
//                signDetail.setExt(ext.toJSONString());
//                signDetail.setSkuId(detail.getSkuId());
//
//                OrderShippingDetail shippingDetail = detailMap.get(itemCode);
//                signDetail.setItemId(shippingDetail.getItemId());
//                signDetail.setSkuName(detail.getSkuName());
//                signDetail.setSaleUnit(detail.getSaleUnit());
//                signDetail.setQty(detail.getQty());
//                signDetail.setStatus(1);
//                signDetail.setCreatedAt(time);
//                signDetail.setUpdatedAt(time);
//                signDetail.setZoneId(orderHead.getRegionCode());
//                signDetail.setPrice(detail.getPrice());
//                signDetail.setMoney(detail.getMoney());
//                signDetail.setTmsId(0L);
//                signDetail.setVenderId(orderHead.getVenderId());
//                signDetail.setItemCode(itemCode);
//                // 2019-7-10 TODO 优化
//                signDetail.setSupplierOrg(shippingDetail.getSupplierOrg());
//
//                signDetails.add(signDetail);
//            }
//        } catch (Exception e) {
//            logger.error(logSign + "订单号" + orderHead.getOrderCode() + ",签收计算服务解析明细失败。");
//            logger.error(e.getMessage(), e);
//
//            throw new BusinessException(ReturnCode.REQUEST_FAIL, "签收计算服务解析明细失败");
//        }
//
//        return signDetails;
//    }

//    /**
//     * 通知es
//     *
//     * @param orderCode 订单号
//     * @param osh       发货单详情
//     * @param logSign   唯一标识
//     */
//    private void notifyEs(Long orderCode, OrderShippingHeadWithBLOBs osh, String marketName, String provideId, String logSign) {
//        OrderSignHead oshHead = signOrderService.getSignHeadByOrderId(orderCode, false);
//
//        try {
//            if (oshHead == null) {
//                logger.info("订单" + orderCode + "的签收信息为null");
//                return;
//            }
//            if (StringUtils.isNotBlank(marketName)) {
//                oshHead.setMarketName(marketName);
//            }
//
//            oshHead.setProviderId(provideId);
//
//            JSONObject extObject = JSON.parseObject(oshHead.getExt());
//            JSONObject headInfo = extObject.getJSONObject("head_info");
//            logger.info("订单-" + orderCode + " 的headInfo " + headInfo);
//            //黑狗签收  1 已签收,0未签收
//            String hgReceiptStatus = headInfo.getString("hg_receipt_status");
//            logger.info("订单-" + orderCode + " 的 hgReceiptStatus " + hgReceiptStatus);
//            if (StringUtils.isNotBlank(hgReceiptStatus)) {
//                oshHead.setHgReceiptStatus(Integer.parseInt(hgReceiptStatus));
//            }
//
//            oshHead.setFinalMoney(oshHead.getMoney());
//
//            logger.info(logSign + "ES入参新建签收单是-- " + JsonUtils.obj2Json(oshHead));
//            esProxy.createIndex(oshHead, logSign);
////
//            OrderShippingHeadWithBLOBs oshEs = new OrderShippingHeadWithBLOBs();
//            oshEs.setId(osh.getId());
//            oshEs.setOrderId(osh.getOrderId());
//            oshEs.setShippingOrderId(osh.getShippingOrderId());
//            oshEs.setStatus(2);
//            logger.info(logSign + "ES入参修改发货是-- " + JsonUtils.obj2Json(oshEs));
//            esProxy.editIndex(oshEs, logSign);
//            OrderHeadForEs ohEs = new OrderHeadForEs();
//            ohEs.setOrderCode(orderCode);
//            ohEs.setOrderStatus(OrderStatus.ORDER_SIGN.getIndex());
//            logger.info(logSign + "ES入参修改订单是-- " + JsonUtils.obj2Json(ohEs));
//            esProxy.editIndex(ohEs, logSign);
//
//        } catch (Throwable e) {
//            logger.info(logSign + "订单号" + orderCode + ",生成发货单同步es失败。");
//            logger.info(e.getMessage(), e);
//        }
//    }


//    @Transactional
//    public CommonResult<Object> isCreateReceiptBill(OrderHead orderHead) {
//
//        Long orderCode = orderHead.getOrderCode();
//
//        OrderShippingHeadWithBLOBs osh = shippingService.getBolbs(orderCode);
//        if (osh == null) {
//            throw new BusinessException(ReturnCode.REQUEST_FAIL, "此订单未生成发货单.请查询");
//        }
//
//        if (OrderFactory.getUserType(orderHead) == UserType.KA.getIndex()) {
//            return this.isCreateReceiptBillForKA();
//        } else {
//            OrderSignHead oshHead = signOrderService.getSignHeadByOrderId(orderCode, false);
//            return isCreateReceiptBillForNormal(oshHead);
//        }
//
//    }

    /**
     * @return CommonResult<Object>
     */
    private CommonResult<Object> isCreateReceiptBillForKA() {
        CommonResult<Object> res = new CommonResult<>();

        res.setCode(ReturnCode.REQUEST_SUCCESS);
        res.setMessage("ok");

        return res;
    }

    /**
     * @param oshHead 签收单信息
     * @return CommonResult<Object>
     */
    private CommonResult<Object> isCreateReceiptBillForNormal(OrderSignHead oshHead) {
        CommonResult<Object> res = new CommonResult<>();
        if (oshHead != null && oshHead.getPayStatus() == 2) {
            res.setCode(ReturnCode.REQUEST_SUCCESS);
            res.setMessage("ok");
        } else {
            res.setCode(ReturnCode.RECEIPT_NO_DEAL);
            res.setMessage("【KA】暂无法操作签收，请先完成线上支付再重试。");
        }

        return res;
    }

}
